import { Component, OnInit } from '@angular/core';
import * as moment from 'moment';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { FetchService } from '../../../../core/net/fetch.service';
import { OneMapService } from '../../../one-map/one-map.service';
import { NzMessageService } from 'ng-zorro-antd';
import * as _ from 'lodash';
import { format, startOfMonth, endOfMonth, subMonths, subDays } from 'date-fns';
import { BehaviorSubject } from 'rxjs';
import { UtilService } from '../../../../core/util/util.service';

@Component({
    selector: 'app-agri-irr',
    templateUrl: './agri-irr.component.html',
    styleUrls: ['./agri-irr.component.scss', '../agriculture.component.scss']
})
export class AgriIrrComponent implements OnInit {
    radioValue = 'single';
    treeValue = '23';
    listData = [];
    cropList = [];
    featureList = [];
    defaultKeys = [];
    stadiaCode: string; //  当前测站编码
    stationName: string;
    yearValue = 2020;
    monthPickerValue;
    topDateModal = [startOfMonth(subMonths(new Date(), 1)), subDays(new Date(), 1)];    //  顶部日期选择 默认上月至今
    topDateChanged = new BehaviorSubject(this.topDateModal);
    topDateRanges = {
        '昨日': [
            moment().subtract(1, 'days').valueOf(),
            moment().subtract(1, 'days').valueOf()
        ],
        '3日': [
            moment().subtract(3, 'days').valueOf(),
            new Date()
        ],
        '7日': [
            moment().subtract(7, 'days').valueOf(),
            new Date()
        ],
        '本月': [
            moment().startOf('month').valueOf(),
            new Date()
        ],
        '上月': [
            moment().subtract(1, 'months').startOf('month').valueOf(),
            moment().subtract(1, 'months').endOf('month').valueOf()
        ],
        '近3月': [
            moment().subtract(3, 'months').startOf('month').valueOf(),
            new Date()
        ]
    };
    processOpt: any = {
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                    show: true,
                    excludeComponents: ['toolbox'],
                    pixelRatio: 2
                }
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                animation: false,
                label: {
                    backgroundColor: '#505765'
                }
            }
        },
        legend: {
            data: ['用水量', '灌溉进度'],
            bottom: 10
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: [
            {
                name: '用水量(万m³)',
                type: 'value'
            },
            {
                name: '灌溉进度(万亩)',
                type: 'value'
            }
        ],
        series: [
            {
                name: '用水量',
                type: 'line',
                smooth: true,
                data: []
            }
        ]
    };
    processOptChange: any = {};
    avgAreaUseOptChange: any = {};
    processEchartsIntance: any;
    featureForm: FormGroup;
    flag: any;  //  1-夏秋灌 2-冬灌
    useWaterTotal = 0;
    irrProgressTotal = 0;
    featureModel: any;
    /*****************  旬月特征值对比  *********************/
    monthForm: FormGroup;
    startValue: Date | null = null;
    endValue: Date | null = null;
    endOpen = false;
    monthData: any = {};
    monthOpt: any = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: [],
            bottom: 0
        },
        grid: {
            top: '10%',
            bottom: '8%',
            left: '6%',
            right: '4%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: {
            type: 'value'
        },
        series: []
    };
    monthOptChange: any = {};
    /******************* end *******************/

    /******************* 监测数据 *******************/
    tableData = [];
    tableHead = [];
    pageNum = 1;
    pageSize = 25;
    /******************* end *******************/


    /******************* 历史同期对比 *******************/
    historyForm: FormGroup;
    historyYearList = [];
    startHistoryValue: Date | null = null;
    endHistoryValue: Date | null = null;
    endHistoryOpen = false;
    historyOpt: any = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: []
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                type: 'line',
                data: []
            }
        ]
    };
    historyOptChange: any = {};

    /******************* end *******************/
    constructor(private fetchService: FetchService,
                private mapService: OneMapService,
                private message: NzMessageService,
                private util: UtilService,
                private fb: FormBuilder) {
        this.featureForm = this.fb.group({
            maxVal: [''],
            minVal: [''],
            maxTime: [''],
            minTime: [''],
            avgVal: [''],
            medianVal: [''],
            last3AvgVal: [''],
            last3MedianVal: ['']
        });
        this.monthForm = this.fb.group({
            valType: ['1'],
            dateType: ['1'],
            plantId: new FormControl({value: null, disabled: true}),
            startYear: [moment().subtract(10, 'year').valueOf()],
            endYear: [new Date()],
            currYear: [moment().year()]
        });
        this.historyYearList = this.getLastSeveralYears();
        this.historyForm = this.fb.group({
            valType: ['val1'],
            yearStr: [[moment().year()]],
            plantId: new FormControl({value: null, disabled: true}),
            startDateStr: [startOfMonth(new Date())],
            endDateStr: [new Date()]
        });
        this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {
            apicode: '24'
        }).subscribe(res => {
            this.cropList = res;
            this.topDateChanged.subscribe(date => {

                if (moment(date[0]).month() < 3 || moment(date[0]).month() > 8) {
                    this.featureList = [
                        {
                            name: '用水量',
                            id: 'useWater'
                        },
                        {
                            name: '灌溉面积',
                            id: 'sumArea'
                        }
                    ];
                } else {
                    const list = this.cropList.map(item => {
                        return {
                            name: item.name,
                            id: item.id
                        };
                    });
                    const initList: Array<any> = [
                        {
                            name: '用水量',
                            id: 'useWater'
                        }
                    ];
                    this.featureList = [...initList, ...list];
                }
                this.featureModel = this.featureList[0].id;

                if (this.radioValue === 'single' && this.stadiaCode) {
                    //  冬灌， 特征值不可选作物
                    this.queryInfo();
                }
            });
            // this.featureList = [
            //     {
            //         name: '用水量',
            //         id: 'useWater'
            //     }
            // ];
            // this.featureModel = this.featureList[0].id;
        });
    }

    ngOnInit() {
        this.selectionChanged();
    }

    selectionChanged() {
        if (this.radioValue === 'single') {
            this.getListData();
        }
    }

    getListData() {
        this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {
            apicode: this.treeValue
        }).subscribe(res => {
            // console.log(res);
            res.forEach(item => {
                item.title = item.name;
                item.key = item.id;
                item.isLeaf = true;
            });
            this.listData = res;
            this.defaultKeys = [this.listData[0].key];
            this.stadiaCode = this.defaultKeys[0];
            this.stationName = this.listData[0].title;
            this.historyTypeChanged('val1');
            this.queryInfo();
        });
    }

    disabledStartDate = (startValue: Date): boolean => {
        if (!startValue || !this.endValue) {
            return false;
        }
        return startValue.getTime() > this.endValue.getTime();
    }

    disabledEndDate = (endValue: Date): boolean => {
        if (!endValue || !this.startValue) {
            return false;
        }
        return endValue.getTime() <= this.startValue.getTime();
    }

    onStartChange(date: Date): void {
        this.startValue = date;
    }

    onEndChange(date: Date): void {
        this.endValue = date;
    }

    handleStartOpenChange(open: boolean): void {
        if (!open) {
            this.endOpen = true;
        }
        // console.log('handleStartOpenChange', open, this.endOpen);
    }

    handleEndOpenChange(open: boolean): void {
        // console.log(open);
        this.endOpen = open;
    }

    /**********************  历史对比 ************************/
    disabledHistoryStartDate = (startValue: Date): boolean => {
        if (!startValue || !this.endHistoryValue) {
            return false;
        }
        return startValue.getTime() > this.endHistoryValue.getTime();
    }

    disabledHistoryEndDate = (endValue: Date): boolean => {
        if (!endValue || !this.startHistoryValue) {
            return false;
        }
        return endValue.getTime() <= this.startHistoryValue.getTime() ||
            moment(endValue.getTime()).year() !== moment(this.startHistoryValue.getTime()).year() ||
            moment(endValue.getTime()).month() > 8 && moment(this.startHistoryValue.getTime()).month() <= 8 ||
            moment(endValue.getTime()).month() >= 3 && moment(this.startHistoryValue.getTime()).month() < 3;
    }

    onStartHistoryChange(date: Date): void {
        this.startHistoryValue = date;
    }

    onEndHistoryChange(date: Date): void {
        this.endHistoryValue = date;
    }

    handleStartHistoryOpenChange(open: boolean): void {
        if (!open) {
            this.endHistoryOpen = true;
        }
    }

    handleEndHistoryOpenChange(open: boolean): void {
        this.endHistoryOpen = open;
    }

    /**********************************************/
    selectedAreaChanged(event): void {
        this.stationName = event.selectedKeys[0].title;
        this.stadiaCode = event.selectedKeys[0].key;
        this.queryInfo();
    }

    yearPickerChange(e): void {
        const start = startOfMonth(new Date(e, this.monthPickerValue || moment().month(), 1));
        const end = endOfMonth(new Date(e, this.monthPickerValue || moment().month(), 1));
        this.topDateModal = [start, end];
        this.topDateChanged.next(this.topDateModal);
    }

    monthPickerChange(e): void {
        const start = startOfMonth(new Date(this.yearValue || moment().year(), e, 1));
        const end = endOfMonth(new Date(this.yearValue || moment().year(), e, 1));
        this.topDateModal = [start, end];
        this.topDateChanged.next(this.topDateModal);
    }

    rangePickerValueChange(e): void {
        if (moment(e[0]).year() !== moment(e[1]).year()) {
            this.message.error('请勿跨年选择');
        } else {
            if (e[0] && e[1]) {
                if ((moment(e[0]).month() < 3 && moment(e[1]).month() >= 3) || (moment(e[0]).month() < 9 && moment(e[1]).month() >= 9)) {
                    this.message.error('请勿跨灌季选择');
                } else {
                    this.queryInfo();
                }
            }
        }
    }

    queryInfo(): void {
        // console.log(this.topDateModal);
        this.onQueryProcessList();
        this.onQueryMonthList();
        this.onQueryHistory();
    }

    private getItemValues(list, key) {
        return list.map(i => {
            return i[key] || 0;
        });
    }

    featureChanged(e): void {
        const params = {
            stDate: moment(this.topDateModal[0]).format('YYYY-MM-DD'),
            edDate: moment(this.topDateModal[1]).format('YYYY-MM-DD'),
            valType: this.featureModel
        };
        if (this.treeValue === '23') {
            _.assign(params, {
                dId: this.stadiaCode
            });
        } else if (this.treeValue === '22') {
            _.assign(params, {
                frId: this.stadiaCode
            });
        }
        this.fetchService.post('report/irr/data', params).subscribe(res => {
            if (res) {
                this.featureForm.patchValue(res);
            }
        });

    }

    private calcYAxisData(type: string, max: number, min: number): number {
        if (type === 'max') {
            return max + (max - min) / 2;
        } else if (type === 'min') {
            return (min - (max - min)) >= 0 ? +(min - (max - min)) : 0;
        }
    }

    onQueryProcessList(): void {
        this.tableHead = [];
        const params = {
            stDate: moment(this.topDateModal[0]).format('YYYY-MM-DD'),
            edDate: moment(this.topDateModal[1]).format('YYYY-MM-DD'),
            valType: this.featureModel
        };
        if (this.treeValue === '23') {
            _.assign(params, {
                dId: this.stadiaCode
            });
        } else if (this.treeValue === '22') {
            _.assign(params, {
                frId: this.stadiaCode
            });
        }
        this.fetchService.post('report/irr/data', params).subscribe(res => {
            if (res) {
                const list = res['originalDataList'];
                this.featureForm.patchValue(res);
                this.useWaterTotal = res['sumUseWater'];
                this.irrProgressTotal = res['sumIrrArea'];
                this.flag = res['flag'];
                const chartName = `${this.stationName} 用水量与灌溉进度过程线`;
                let legendArr = [];
                this.tableHead = res['plantList'].map((item, idx) => {
                    return {
                        name: item.name,
                        id: 'val' + (idx + 1)
                    };
                });
                if (this.flag === 1) {
                    // const keyList = Object.keys(list);
                    legendArr = [{
                        name: '用水量',
                        id: 'useWater'
                    }];
                    res['plantList'].forEach((plant, idx) => {
                        legendArr.push({
                            id: 'val' + (idx + 1),
                            name: plant.name
                        });
                    });
                } else if (this.flag === 2) {
                    legendArr = [
                        {
                            name: '用水量',
                            id: 'useWater'
                        }, {
                            name: '总灌溉面积',
                            id: 'winterArea'
                        }
                    ];
                }
                let rtMax;
                let rtMin;
                let ltMax;
                let ltMin;
                const seriesData = legendArr.map((o, idx) => {
                    const data = [];
                    list.forEach(item => {
                        if (typeof item[o.id] !== 'undefined') {
                            data.push(item[o.id]);
                        }
                    });
                    if (idx == 0) {
                        rtMax = this.util.max(data);
                        rtMin = this.util.min(data);
                    } else if (idx == 1) {
                        ltMax = this.util.max(data);
                        ltMin = this.util.min(data);
                    } else {
                        ltMax = this.util.max(data.concat(ltMax));
                        ltMin = this.util.min(data.concat(ltMin));
                    }
                    return {
                        name: o.name,
                        type: 'line',
                        smooth: true,
                        yAxisIndex: idx > 0 ? 1 : 0,
                        markPoint: {
                            // symbol: 'diamond',
                            symbolSize: 30,
                            data: [
                                {
                                    type: 'max',
                                    name: '最大'
                                },
                                {
                                    name: '最小',
                                    type: 'min'
                                }
                            ],
                            label: {
                                normal: {
                                    formatter: (p) => {
                                        // console.log(p);
                                        return `${p.name}: ${p.value}`;
                                    }
                                }
                            }
                        },
                        data: data
                    };
                });

                this.processOptChange = {
                    legend: {
                        data: legendArr.map(item => {
                            return item.name;
                        })
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {
                                name: chartName
                            }
                        }
                    },
                    xAxis: {
                        data: list.map(o => {
                            return o.time;
                        })
                    },
                    yAxis: [
                        {
                            name: '用水量(万m³)',
                            type: 'value',
                            min: Math.floor(this.calcYAxisData('min', rtMax, rtMin)),
                            max: Math.ceil(this.calcYAxisData('max', rtMax, rtMin))
                        },
                        {
                            name: '灌溉进度(万亩)',
                            type: 'value',
                            min: Math.floor(this.calcYAxisData('min', ltMax, ltMin)),
                            max: Math.ceil(this.calcYAxisData('max', ltMax, ltMin))
                        }
                    ],
                    series: seriesData
                };
                this.avgAreaUseOptChange = {
                    legend: {
                        data: ['亩均用水量']
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {
                                name: `${this.stationName} 亩均用水量曲线`
                            }
                        }
                    },
                    xAxis: {
                        data: list.map(o => {
                            return o.time;
                        })
                    },
                    series: [{
                        name: '亩均用水量',
                        type: 'line',
                        data: list.map(o => {
                            return o['avgAreaUse'];
                        })
                    }]
                };
                this.tableData = list;
            }
        });
    }

    xunTypeChanged(data): void {
        console.log(data);
        if (data === '4' || data === '5' || data === '6') {
            this.monthForm.get('plantId').enable();
        } else {
            this.monthForm.get('plantId').disable();
            this.monthForm.patchValue({
                plantId: null
            });
        }
    }

    historyTypeChanged(data): void {
        //  类型为灌溉面积 且 时间为春夏灌（4-9月）
        if ((data === 'val1' || data === 'valTotal1') &&
            moment(this.historyForm.value.startDateStr).month() >= 3 &&
            moment(this.historyForm.value.startDateStr).month() <= 8) {
            this.historyForm.get('plantId').enable();
            this.historyForm.patchValue({
                plantId: this.cropList[0].id
            });
        } else {
            this.historyForm.get('plantId').disable();
            this.historyForm.patchValue({
                plantId: (data === 'val1' || data === 'valTotal1') ? '7' : '6'
            });
        }
    }

    onQueryMonthList(): void {
        console.log(this.monthForm.value);
        const params = {
            // trId: this.stadiaCode,
            stYear: moment(this.monthForm.value.startYear).year(),
            edYear: moment(this.monthForm.value.endYear).year(),
            dateType: this.monthForm.value.dateType,
            valType: this.monthForm.value.valType,
            plantId: this.monthForm.value.plantId
        };
        if (this.treeValue === '23') {
            _.assign(params, {
                dId: this.stadiaCode
            });
        } else if (this.treeValue === '22') {
            _.assign(params, {
                frId: this.stadiaCode
            });
        }
        this.fetchService.post('report/irr/monthXunCampare', params).subscribe(res => {
            if (res && Array.isArray(res)) {
                this.monthOptChange = {
                    legend: {
                        data: res.map(o => {
                            return o.year === 'thisYear' ? '当前年' : '历史年';
                        })
                    },
                    xAxis: {
                        data: res[0].list.map(o => {
                            return o.m;
                        })
                    },
                    series: res.map(o => {
                        return {
                            name: o.year === 'thisYear' ? '当前年' : '历史年',
                            type: 'bar',
                            data: o.list.map(item => {
                                return item.val;
                            })
                        };
                    })
                };
            }
        });
    }

    onQueryHistory(): void {
        console.log(this.historyForm.value);
        let plantId;
        if (this.historyForm.value.plantId) {
            plantId = this.historyForm.value.plantId;
        } else {
            plantId = (this.historyForm.value.valType === 'val1' || this.historyForm.value.valType === 'valTotal1') ? '7' : '6';
        }
        const params = {
            stDate: moment(this.historyForm.value.startDateStr).format('MM-DD'),
            edDate: moment(this.historyForm.value.endDateStr).format('MM-DD'),
            years: this.historyForm.value.yearStr.join(','),
            plantId: plantId
        };
        if (this.treeValue === '23') {
            _.assign(params, {
                dId: this.stadiaCode
            });
        } else if (this.treeValue === '22') {
            _.assign(params, {
                frId: this.stadiaCode
            });
        }
        this.fetchService.post('report/irr/hisCampare', params).subscribe(res => {
            if (res && Array.isArray(res)) {
                const prop = this.historyForm.value.valType.substring(0, this.historyForm.value.valType.length - 1);
                this.historyOptChange = {
                    legend: {
                        data: res.map(o => {
                            return o.year;
                        })
                    },
                    xAxis: {
                        data: res[0].list.map(o => {
                            return moment(o.time).format('MM-DD HH:mm:ss');
                        })
                    },
                    series: res.map(o => {
                        return {
                            name: o.year,
                            type: 'line',
                            // smooth: true,
                            data: o.list.map(item => {
                                return item[prop];
                            })
                        };
                    })
                };
            }
        });
    }

    private getLastSeveralYears(length = 10): Array<any> {
        const curYear = moment().year();
        const arr = [];
        for (let i = curYear - length; i <= curYear; i++) {
            arr.push(i);
        }
        return arr;
    }
}
